//
//  QRViewController.m
//  QRWeiXinDemo
//
//  Created by lovelydd on 15/4/25.
//  Copyright (c) 2015年 lovelydd. All rights reserved.
//

#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "QRView.h"
#import "NewsDetailViewController.h"
#import "NewsWebViewController.h"
#import "UIControl+Blocks.h"
#import "SpecialNewsListViewController.h"
#import "ServiceNews.h"
#import "AccountManager.h"
#import "RCDLiveChatRoomLSViewController.h"
#import "RCDLiveChatRoomViewController.h"
#import "UIViewController+HUD.h"
#import "RCDLive.h"

@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate,QRViewDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    
    NSString * aid;
}

@property (strong, nonatomic) AVCaptureDevice * device;
@property (strong, nonatomic) AVCaptureDeviceInput * input;
@property (strong, nonatomic) AVCaptureMetadataOutput * output;
@property (strong, nonatomic) AVCaptureSession * session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer * preview;

@property (assign,nonatomic) BOOL isLighting;

@end

@implementation QRViewController

- (void)viewWillAppear:(BOOL)animated
{
    if(self.isBack) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden= YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    self.view.backgroundColor = [UIColor clearColor];
    [self setupCamera];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self removeCamera];
    //[timer invalidate];
}

- (void)removeCamera
{
    [_preview removeFromSuperlayer];
    [_session stopRunning];
}

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    //    _preview.backgroundColor=(__bridge CGColorRef)([UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.7f]);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isBack = NO;
    
    CGRect screenRect = [UIScreen mainScreen].bounds;
    QRView *qrRectView = [[QRView alloc] initWithFrame:screenRect];
    qrRectView.transparentArea = CGSizeMake(200, 200);
    qrRectView.backgroundColor = [UIColor clearColor];
    qrRectView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    qrRectView.delegate = self;
    [self.view addSubview:qrRectView];
    
    UIButton *pop = [UIButton buttonWithType:UIButtonTypeCustom];
    pop.frame = CGRectMake(20, 20, 50, 50);
    [pop setTitle:@"返回" forState:UIControlStateNormal];
    [pop addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pop];
    
    //修正扫描区域
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat screenWidth = self.view.frame.size.width;
    CGRect cropRect = CGRectMake((screenWidth - qrRectView.transparentArea.width) / 2,
                                 (screenHeight - qrRectView.transparentArea.height) / 2,
                                 qrRectView.transparentArea.width,
                                 qrRectView.transparentArea.height);

    [_output setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
                                          cropRect.origin.x / screenWidth,
                                          cropRect.size.height / screenHeight,
                                          cropRect.size.width / screenWidth)];
    
    __weak typeof(self) weak_self = self;
    
    UIButton *folderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    folderButton.frame = CGRectMake(69, cropRect.origin.y - 53 - 78, 48, 78);
    [folderButton setTitle:@"图片" forState:UIControlStateNormal];
    folderButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);//设置image在button上的位置（上top，左left，下bottom，右right）这里可以写负值，对上写－5，那么image就象上移动5个像素
    folderButton.titleLabel.font = [UIFont systemFontOfSize:16];//title字体大小
    folderButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [folderButton setImage:[UIImage imageNamed:@"folder"] forState:UIControlStateNormal];
    folderButton.titleEdgeInsets = UIEdgeInsetsMake(88, - folderButton.titleLabel.bounds.size.width - 45, 0, 0);//设置title在button上的位置（上top，左left，下bottom，右right）
    [folderButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.allowsEditing = YES;
        picker.delegate = weak_self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weak_self presentViewController:picker animated:YES completion:^{}];
    }];
    [self.view addSubview:folderButton];
    
    UIButton *lightingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lightingButton.frame = CGRectMake(screenRect.size.width - 69 - 48, cropRect.origin.y - 53 - 78, 48, 78);
    [lightingButton setTitle:@"灯光" forState:UIControlStateNormal];
    lightingButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);//设置image在button上的位置（上top，左left，下bottom，右right）这里可以写负值，对上写－5，那么image就象上移动5个像素
    lightingButton.titleLabel.font = [UIFont systemFontOfSize:16];//title字体大小
    lightingButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [lightingButton setImage:[UIImage imageNamed:@"light_normal"] forState:UIControlStateNormal];
    lightingButton.titleEdgeInsets = UIEdgeInsetsMake(88, - folderButton.titleLabel.bounds.size.width - 45, 0, 0);//设置title在button上的位置（上top，左left，下bottom，右right）
    __weak UIButton *weak_lightingButton = lightingButton;
    [lightingButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        if (weak_self.isLighting) {
            weak_self.isLighting = NO;
            [weak_self turnOffLed];
            [weak_lightingButton setImage:[UIImage imageNamed:@"light_normal"] forState:UIControlStateNormal];
        } else {
            weak_self.isLighting = YES;
            [weak_self turnOnLed];
            [weak_lightingButton setImage:[UIImage imageNamed:@"light_checked"] forState:UIControlStateNormal];
        }
    }];
    [self.view addSubview:lightingButton];

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self dismissViewControllerAnimated:YES completion:^{
        [self getURLWithImage:image];
    }];
}

- (void)getURLWithImage:(UIImage *)img
{
    // 创建一个CIImage对象
    CIImage *ciImage = [[CIImage alloc] initWithCGImage:img.CGImage options:nil];
    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer:@(YES)}]; // 软件渲染
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];// 二维码识别
    // 注意这里的CIDetectorTypeQRCode
    NSArray *features = [detector featuresInImage:ciImage];
    for (CIQRCodeFeature *feature in features) {
        NSLog(@"msg = %@",feature.messageString); // 打印二维码中的信息
    }
    
    if ([features count] > 0) {
        CIQRCodeFeature *f = features[0];
        [self doSomeByGetResultString:f.messageString];
    } else {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"解析失败" message:@"请检查图片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
    }
    
    //TODO lishiyang
    
//    UIImage *loadImage          = img;
//    CGImageRef imageToDecode    = loadImage.CGImage;
//
//    ZXLuminanceSource *source   = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
//    ZXBinaryBitmap *bitmap      = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
//
//    NSError *error              = nil;
//
//    ZXDecodeHints *hints        = [ZXDecodeHints hints];
//
//    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
//    ZXResult *result            = [reader decode:bitmap
//                                hints:hints
//                                error:&error];
//    if (result) {
//        // The coded result as a string. The raw data can be accessed with
//        // result.rawBytes and result.length.
//        [self doSomeByGetResultString:result.text];
//    } else {
//        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"解析失败" message:@"请检查图片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alter show];
//    }
}

- (void)pop:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark QRViewDelegate
-(void)scanTypeConfig:(QRItem *)item {
    
    if (item.type == QRItemTypeQRCode) {
        _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
        
    } else if (item.type == QRItemTypeOther) {
        
        _output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                        AVMetadataObjectTypeEAN8Code,
                                        AVMetadataObjectTypeCode128Code,
                                        AVMetadataObjectTypeQRCode];
    }
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    if ([metadataObjects count] >0)
    {
        //停止扫描
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    DebugLog(@"stringValue =  %@",stringValue);

    [self doSomeByGetResultString:stringValue];
}

- (void)doSomeByGetResultString:(NSString *)stringValue
{
    NSString *str = @"http:";
    
    self.isBack = YES;
    //在str1这个字符串中搜索\n，判断有没有
    
    if ([stringValue rangeOfString:str].location != NSNotFound) {
        DebugLog(@"stringValue = %@",stringValue);
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"获取内容错误" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    
    NSArray *strarray  = [stringValue componentsSeparatedByString:@".html"];

    NSArray * aidarray = [strarray[0] componentsSeparatedByString:@"/"];
    aid                = [aidarray objectAtIndex:[aidarray count]-1];
    DebugLog(@"%@",strarray[0]);
    DebugLog(@"aid     = %@",[aidarray objectAtIndex:[aidarray count]-1]);
    
    if (self.qrUrlBlock) {
        self.qrUrlBlock(stringValue);
    }
    if ([stringValue rangeOfString:@"type=live"].location != NSNotFound) {
        //视频直播
        [self queryLiveAndShowPlayChatRoom:stringValue];
    } else if ([stringValue rangeOfString:@"aid="].location != NSNotFound) {
        //普通新闻详情，需要请求详情，拼接HTML
        NewsDetailViewController *controller = [NewsDetailViewController new];
        controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,[[stringValue componentsSeparatedByString:@"="] lastObject]];
        [self showViewController:controller sender:self];
    }
    else if ([stringValue rangeOfString:@"specialid="].location != NSNotFound)
    {
        SpecialNewsListViewController *specialNewsListViewController = [[SpecialNewsListViewController alloc] init];
        specialNewsListViewController.subURL              = [NSString stringWithFormat:@"%@&%@",URL_SUB_GET_SPECIAL_NEWS,[[stringValue componentsSeparatedByString:@"?"] lastObject]];
        [self showViewController:specialNewsListViewController sender:nil];
    }
    else
    {
        NewsWebViewController *newsWebViewController = [NewsWebViewController new];
        if ([AccountManager sharedAccountManager].f_isLogined) {
            if ([stringValue rangeOfString:@"?"].location != NSNotFound) {
                stringValue = [stringValue stringByAppendingString:[NSString stringWithFormat:@"&userid=%@",[AccountManager sharedAccountManager].f_uid]];
            }else {
                stringValue = [stringValue stringByAppendingString:[NSString stringWithFormat:@"?userid=%@",[AccountManager sharedAccountManager].f_uid]];
            }
        }
        newsWebViewController.urlString              = stringValue;
        [self showViewController:newsWebViewController sender:nil];
    }
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [_session startRunning];
}

-(void)turnOffLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

-(void)turnOnLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOn];
        [device unlockForConfiguration];
    }   

}



- (NSString *) paramValueOfUrl:(NSString *) url withParam:(NSString *) param{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",param];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return nil;
}

-(void)queryLiveAndShowPlayChatRoom:(NSString *)scanurl
{
    NSString *subURL=@"http://www3.ctdsb.net/index.php?m=live&c=index&a=index";
    
    NSString *playID = nil;
    playID = [self paramValueOfUrl:scanurl withParam:@"lid"];
    if(playID==nil) {
        playID = @"29";
    }
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doPlayNewsDetail:subURL lid:playID type:@"live" success:^(id responseObject, NSString *message) {
        M_PlayNewsDetail *playdetail = responseObject;
        [weak_self loginRongCloud:scanurl play:playdetail];
    } failure:^(NSString *message) {
        [self showHUDText:@"新闻信息已失效或不是视频新闻"];
    }];
    
    
}

/**
 *登录融云，这里只是为了演示所以直接调融云的server接口获取token来登录，为了您的app安全，这里建议您通过你们自己的服务端来获取token。
 *
 */
-(void)loginRongCloud:(NSString *)scanurl_ play:(M_PlayNewsDetail *) play_
{
    NSString *videoUrl = play_.f_rtmp;
    //525l561af388sbrhag97hgqctc6
    //518fqprke2491aq2s8obqm4qj30
//    videoUrl = @"rtmp://d.rtmp.playlive.ws.v.btime.com/live_btime_r/518fqprke2491aq2s8obqm4qj30";
    //155952
//    videoUrl =@"http://playback.ws.v.btime.com/live_btime_r-55smi46fqi781nouh527sfness8--20170307173032.m3u8";
    
    NSString *userId = nil;
    NSString *userName = nil;
    NSString *userProtrait = @"";
    
    NSString *url = @"http://www3.ctdsb.net/index.php?m=live&c=rongyun&a=token";
    
    AFHTTPSessionManager *mgr = [ServiceUtils commonHTTPManager];
    long timestamp = (long)[[NSDate date] timeIntervalSince1970];
    __weak __typeof(&*self)weakSelf = self;
    
    // 2.拼接请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if ([AccountManager sharedAccountManager].f_isLogined) {
        userId =[AccountManager sharedAccountManager].f_uid;
        userProtrait =[AccountManager sharedAccountManager].f_user_img;
        userName =[AccountManager sharedAccountManager].f_nickname;
    }else {
        userId = [NSString stringWithFormat:@"u%ld",timestamp];
        userProtrait =@"";
        userName =@"匿名网友";
        [self showHUDText:@"未登录也可看直播新闻"];
    }
    parameters[@"userId"]= userId;
    parameters[@"name"]= userName;
    parameters[@"portraitUri"]= userProtrait;
    
    [mgr POST:url parameters:parameters progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
          NSLog(@"loginRongCloud OK");
          NSNumber *code = responseObject[@"code"];
          if (code.intValue == 200) {
              NSString *token = responseObject[@"token"];
              NSString *userId = responseObject[@"userId"];
              
              [[RCDLive sharedRCDLive] connectRongCloudWithToken:token success:^(NSString *loginUserId) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      RCUserInfo *playuser = [[RCUserInfo alloc] init];
                      playuser.userId = userId;
                      playuser.portraitUri = userProtrait;
                      playuser.name=userName;
                      [RCIMClient sharedRCIMClient].currentUserInfo=playuser;
                      if([play_.f_orient_type isEqualToString:@"1"]) {
                          //横屏
                          RCDLiveChatRoomLSViewController *chatRoomVC = [[RCDLiveChatRoomLSViewController alloc]init];
                          chatRoomVC.conversationType = ConversationType_CHATROOM;
                          chatRoomVC.targetId = play_.f_id;
                          chatRoomVC.targetName = play_.f_title;
                          chatRoomVC.contentURL = videoUrl;
                          chatRoomVC.shareUrl = scanurl_;
                          chatRoomVC.isScreenVertical = NO;//竖屏
                          chatRoomVC.playDetail = play_;
                          chatRoomVC.hidesBottomBarWhenPushed = YES;
                          [self.navigationController setNavigationBarHidden:YES];
                          [self.navigationController pushViewController:chatRoomVC animated:NO];
                      }else {
                          RCDLiveChatRoomViewController *chatRoomVC = [[RCDLiveChatRoomViewController alloc]init];
                          chatRoomVC.conversationType = ConversationType_CHATROOM;
                          chatRoomVC.targetId = play_.f_id;
                          chatRoomVC.targetName = play_.f_title;
                          chatRoomVC.contentURL = videoUrl;
                           chatRoomVC.shareUrl = scanurl_;
                          chatRoomVC.isScreenVertical = NO;//竖屏
                          chatRoomVC.playDetail = play_;
                          chatRoomVC.hidesBottomBarWhenPushed = YES;
                          [self.navigationController setNavigationBarHidden:YES];
                          [self.navigationController pushViewController:chatRoomVC animated:NO];
                      }
                  });
              } error:^(RCConnectErrorCode status) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                  });
                  
              } tokenIncorrect:^{
                  dispatch_async(dispatch_get_main_queue(), ^{
                      
                  });
              }];
              
              dispatch_async(dispatch_get_main_queue(), ^{
                  [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
              });
              
          } else {
              dispatch_async(dispatch_get_main_queue(), ^{
                  [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                  
              });
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          //         NSLog( @"出错了");
          dispatch_async(dispatch_get_main_queue(), ^{
              [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
          });
          
      }];
}



@end
